package com.changgou.files.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.files.util.FastDFSClient;
import com.changgou.files.util.FastDFSFile;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/file")
public class Files {

    @PostMapping("/upload")
    public Result upload(MultipartFile file){

        try {
            //1.判断文件是否为空
            if (file.isEmpty()) {
                return new Result(false, StatusCode.ERROR, "文件不存在");
//                throw new RuntimeException("文件不存在");
            }
            //2.获取文件名称，为空也抛异常
            String originalFilename = file.getOriginalFilename();
            if (StringUtils.isEmpty(originalFilename)) {
//                throw new RuntimeException("文件不存在");
                return new Result(false, StatusCode.ERROR, "文件不存在");
            }
            //3.获取文件后缀名
            String last = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            //获取文件内容
            byte[] content = file.getBytes();
            //4.封装为FastDFSClient/upload/的入参 - FastDFSFile
            FastDFSFile fastDFSFile = new FastDFSFile(originalFilename, content, last);
            //5.调用FastDFSClient上传方法
            String[] upload = FastDFSClient.upload(fastDFSFile);
            //6.封装返回结果
            String url = FastDFSClient.getTrackerUrl() + upload[0] + "/" + upload[1];
            return new Result(true, StatusCode.OK, "文件上传成功", url);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //return new Result(false, StatusCode.ERROR, "文件上传失败");
    }
}